<template>
  <div class="form-border">
    <div class="title info-deep">移交空间</div>
    <el-select
      v-model="userId"
      filterable
      remote
      :remote-method="searchMember"
      placeholder="搜索空间成员"
      :loading="loading"
      class="m-t-10">
      <el-option
        v-for="member in members"
        :key="member.id"
        :label="member.nickname"
        :value="member.id">
        <div class="flex align-items-center">
          <el-avatar :src="member.avatar" size="small" class="m-r-10" />
          {{ member.nickname }}
        </div>
      </el-option>
    </el-select>
    <div class="m-t-10">
      <el-button
        size="small"
        type="primary"
        @click="transferSpace"
        :disabled="!userId">
        确认移交
      </el-button>
    </div>
  </div>
</template>

<script>
import { formatMembers } from '@/components/spaces/settings/members/format';

export default {
  name: 'transfer-space', // 移交空间
  data() {
    return {
      userId: '',
      loading: false,
      members: [],
    };
  },
  methods: {
    searchMember(query) {
      this.loading = true;
      this.$api.spaceMembers.index({
        spaceId: this.$route.params.spaceId,
        searchName: query.trim(),
      }).then((res) => { this.members = formatMembers(res.data); })
        .catch(() => {})
        .then(() => { this.loading = false; });
    },
    transferSpace() {
      this.$msgbox({
        title: '移交空间',
        message: '<div>移交空间后，当前账户权限会变成空间管理员。确认移交本空间吗？</div>',
        dangerouslyUseHTMLString: true,
        showCancelButton: true, // 显示取消按钮
        customClass: 'confirm-left',
        confirmButtonText: '确定',
        confirmButtonLoading: false,
        confirmButtonClass: 'el-button--danger',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false, // 不允许通过点击遮罩层关闭
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            Object.assign(instance, {
              confirmButtonLoading: true,
              confirmButtonText: '正在移交...',
            });

            this.$api.spaces.transfer({
              spaceId: this.$route.params.spaceId,
              userId: this.userId,
            }).then(() => {
              this.$message.success('移交成功');
              this.$router.push(`/spaces/${this.$route.params.spaceId}`);
            }).catch(() => {})
              .then(() => done());
          } else done();
        },
      });
    },
  },
};
</script>

<style></style>
